package com.io.transform;

import org.junit.Test;

import java.io.*;

/**
 * @author ymb
 * @version 1.0
 * 演示 OutputStreamWriter 使用，解决中文编码问题
 * 将 FileOutputStream 字节输出流 转换为 OutputStreamWriter 字符输出流
 * 指定处理方式 gbk/utf-8/utf8
 */
public class OutputStreamWriter_ {
    public static void main(String[] args) throws IOException {
        // 小伙子加油，努力会有不一样的未来，好好读书
        String filePath = "E:\\test\\a.txt";
        String chartSet = "utf8";
        // 1.创建 OutputStreamWriter
        // 把 FileOutputStream 转换成 OutputStreamWriter
        // 按照 gbk 编码方式 写文件内容
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath,true),chartSet);
        // 2.把 OutputStreamWriter 传入 BufferedWriter
        BufferedWriter bw = new BufferedWriter(osw);
        // 写入内容
        bw.newLine();
        bw.write("文件编码方式变更为 "+chartSet);
        bw.newLine();
        bw.write("慢也是一种快！");
        System.out.println("按照编码方式来处理写入文件内容 "+chartSet);
        // 关闭外层资源流
        bw.close();
    }

    @Test
    public void writeContent() throws IOException {
        // 编写内容
        String filePath = "E:\\test\\hello.txt";
        String chartSet = "utf-8";
        // 1.创建 OutputStreamWriter 对象
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath,true),chartSet);
        // 换行
        osw.write("\r\n");
        osw.write("测试乱码问题,居然"+chartSet);
        // 关闭资源流
        osw.close();
    }

    @Test
    public void differentWriter() throws IOException {
        String filePath = "E:\\test\\two.txt";
        String chartSet = "utf-8";
        // 1.创建 OutputStreamWriter 对象
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath,true),chartSet);
        // 创建处理流来写入文件内容
        BufferedWriter bw = new BufferedWriter(osw);
        bw.write("现在写入的是 "+chartSet+" 格式的文本内容");
        bw.newLine();
        bw.write("好好加油好好努力！");
        System.out.println("写入成功！");
        // 关闭资源流
        bw.close();
    }
}
